As with many kinds of apps, there are difficult issues to solve when we write JavaScript apps. In this article, we’ll look at some solutions to common JavaScript problems.
Get Month Name from a Date
We can use the toLocaleString
method to get a month name from a Date
instance.
For example, we can write:
const date = new Date(2020, 10, 10);
const month = date.toLocaleString('default', { month: 'long' });
console.log(month);
'long'
returns the full month name.
'default'
is the locale, which is whatever is set on our computers.
Check if a String is a Valid JSON String in JavaScript
To check is a string is a valid JSON string, we can try parsing it with JSON.parse
.
For instance, we can write:
const isJsonString = (str) => {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
We put JSON.parse
in the try
block so that it’ll throw an exception if it isn’t valid.
Convert String to Title Case
We can convert a string to title case with the replace
method.
For instance, we can write:
str.replace(/wS*/g, (txt) => {
return `${txt.charAt(0).toUpperCase()}${txt.substr(1).toLowerCase()}`;
});
We use the replace
method with a regex to find the first character of each word in a string.
w
is the word boundary. S
is any non-whitespace character.
Then pass in a callback to get the text and return the word with the first letter changed to uppercase and the rest converted to lower case.
Link and Execute External JavaScript File Hosted on GitHub
We can use the GitHub CDN to get the file from Github and run it.
However, since Github disabled hotlinking, we’ve to download the file from the following locations and run it locally.
To do that, we can access the script by writing:
http://raw.githubusercontent.com/<username>/<repo>/<branch>/script.js
or:
http://cdn.jsdelivr.net/gh/<username>/<repo>/script.js
to get the latest version.
We can also get a file by the commit hash by writing:
http://cdn.jsdelivr.net/gh/<username>/<repo>@<version or hash>/script.js
We replace script.js
with our own script file name.
We download from any of those locations and include it ourselves.
Conditionally Add Attributes to React Components
We can conditionally add attributes to React components by writing:
<Button {...(condition ? { bsStyle: 'success' } : {})} />
We return different objects conditionally according to the condition
expression.
Then we can spread the props accordingly.
Remove Object from Array Using JavaScript
There are several ways to remove an object from an array.
We can call arr.shift()
to remove the first element of an array.
Also, we can call arr.slice(1)
to remove the first element of an array.
arr.splice(0, 1)
also removes the first element of an array.
arr.pop()
to remove the last element.
arr.slice(0, a.length — 1)
also removes the last element.
arr.length = arr.length — 1
lets us remove the last element.
arr.splice(index, 1)
removes the element with the given index.
arr.slice(0, x).concat(arr.slice(-x))
remove the element with the index x
.
We can also use filter
to remove items that doesn’t meet the given condition:
const filtered = arr.filter((el) => { return el.name !== "james"; });
Now all items in arr
with el.name
equal to 'james'
is removed and the rest are returned in a new array.
How do I Replace a Character at a Particular Index
Replace a character at the given index.
We can use the substring
method to return a string with the character at the given index replaced.
For instance, we can write:
const s = "Hello world";
const index = 3;
s = `${s.substring(0, index)}x${s.substring(index + 1)}`;
We use substring
to divide the string according to the index into 2.
The index
in the 2nd argument isn’t included.
Max Size of localStorage Values
Local storage can store up to 10MB of data.
However, this can be customized by the user.
How to Initialize an Array’s Length
We can initialize the array’s length with the Array
constructor.
For instance, we can write:
new Array(5);
or:
Array(5);
to create an array with length 5.
Conclusion
We can check if a JSON string is valid by parsing it. To get the name, we can use the toLocaleString
method. Converting strings to title case can be done with the replace
method. There are many ways to remove an item from a JavaScript array.